<?php
/**
 * 同城微聚汇
 * ============================================================================
 * * 版权所有 2015-2027 武汉鼎联信息技术有限公司，并保留所有权利。
 * 网站地址: http://dlshop.dliansoft.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: IT宇宙人 2015-08-10 $
 */
namespace app\mobile\controller;
use think\AjaxPage;
use think\Page;
use think\Db;
use pdo;
class Goods extends MobileBase {
  
    public function index(){
        return $this->fetch();
    }

    /**
     * 分类列表显示
     */
    public function categoryList(){
        return $this->fetch();
    }

    /**
     * 商品分类列表显示
     */
    public function shopcategory(){
        return $this->fetch();
    }

   

    /**
     * 商品列表页
     */
    
    public function goodsList(){
    	$filter_param = array(); // 帅选数组
    	$id = I('id/d',0); // 当前分类id
    	$brand_id = I('brand_id/d',0);
        $type = I('type/d',1);
    	$spec = I('spec',0); // 规格
    	$attr = I('attr',''); // 属性
    	$sort = I('sort','a.goods_id'); // 排序
    	$sort_asc = I('sort_asc','desc'); // 排序
    	$price = I('price',''); // 价钱
    	$start_price = trim(I('start_price','0')); // 输入框价钱
    	$end_price = trim(I('end_price','0')); // 输入框价钱
    	if($start_price && $end_price) $price = $start_price.'-'.$end_price; // 如果输入框有价钱 则使用输入框的价钱   	 
    	$filter_param['id'] = $id; //加入帅选条件中
    	$brand_id  && ($filter_param['brand_id'] = $brand_id); //加入帅选条件中
    	$spec  && ($filter_param['spec'] = $spec); //加入帅选条件中
    	$attr  && ($filter_param['attr'] = $attr); //加入帅选条件中
    	$price  && ($filter_param['price'] = $price); //加入帅选条件中
         
    	$goodsLogic = new \app\home\logic\GoodsLogic(); // 前台商品操作逻辑类
        $qtype = I('qtype','');
        $where['is_on_sale']=1;
        $where['on_time']=array('elt',time());
        $where['off_time']=array('egt',time());
        if($qtype){
            $filter_param['qtype'] = $qtype;
            $where[$qtype] = 1;
        }
    	// 分类菜单显示
       
        if($type==2){
            $goodsCate = M('GoodsCategoryAdmin')->where("id", $id)->find();// 当前分类
            //($goodsCate['level'] == 1) && header('Location:'.U('Home/Channel/index',array('cat_id'=>$id))); //一级分类跳转至大分类馆
            $cateArr = $goodsLogic->get_goods_cate($goodsCate);
            
            // 帅选 品牌 规格 属性 价格
            $cat_id_arr = getCatGrandson_two ($id);
            $filter_goods_id = M('goods')->where("is_on_sale=1 and on_time<=".time()." and off_time>=".time()."")->where("extend_cat_id", "in" ,implode(',', $cat_id_arr))->cache(true)->getField("goods_id",true);
            
        }else{
            $goodsCate = M('GoodsCategory')->where("id", $id)->find();// 当前分类
            //($goodsCate['level'] == 1) && header('Location:'.U('Home/Channel/index',array('cat_id'=>$id))); //一级分类跳转至大分类馆
            $cateArr = $goodsLogic->get_goods_cate($goodsCate);

            // 帅选 品牌 规格 属性 价格
            $cat_id_arr = getCatGrandson ($id);
            $filter_goods_id = M('goods')->where($where)->where("cat_id", "in" ,implode(',', $cat_id_arr))->cache(true)->getField("goods_id",true);
        }
    	
            
        //var_dump($filter_goods_id);
    	//var_dump(M('goods')->getLastSql());
        //exit;
    	// 过滤帅选的结果集里面找商品
    	if($brand_id || $price)// 品牌或者价格
    	{
    		$goods_id_1 = $goodsLogic->getGoodsIdByBrandPrice($brand_id,$price); // 根据 品牌 或者 价格范围 查找所有商品id
    		$filter_goods_id = array_intersect($filter_goods_id,$goods_id_1); // 获取多个帅选条件的结果 的交集
    	}
    	if($spec)// 规格
    	{
    		$goods_id_2 = $goodsLogic->getGoodsIdBySpec($spec); // 根据 规格 查找当所有商品id
    		$filter_goods_id = array_intersect($filter_goods_id,$goods_id_2); // 获取多个帅选条件的结果 的交集
    	}
    	if($attr)// 属性
    	{
    		$goods_id_3 = $goodsLogic->getGoodsIdByAttr($attr); // 根据 规格 查找当所有商品id
    		$filter_goods_id = array_intersect($filter_goods_id,$goods_id_3); // 获取多个帅选条件的结果 的交集
    	}
        //var_dump($filter_goods_id);

        //筛选网站自营,入驻商家,货到付款,仅看有货,促销商品
        $sel =I('sel');
        if($sel)
        {
            $goods_id_4 = $goodsLogic->get_filter_selected($sel,$cat_id_arr);
            $filter_goods_id = array_intersect($filter_goods_id,$goods_id_4);
        }
        //var_dump($filter_goods_id);
    	 
    	$filter_menu  = $goodsLogic->get_filter_menu($filter_param,'goodsList'); // 获取显示的帅选菜单
    	$filter_price = $goodsLogic->get_filter_price($filter_goods_id,$filter_param,'goodsList'); // 帅选的价格期间
    	$filter_brand = $goodsLogic->get_filter_brand($filter_goods_id,$filter_param,'goodsList',1); // 获取指定分类下的帅选品牌
    	$filter_spec  = $goodsLogic->get_filter_spec($filter_goods_id,$filter_param,'goodsList',1); // 获取指定分类下的帅选规格
    	$filter_attr  = $goodsLogic->get_filter_attr($filter_goods_id,$filter_param,'goodsList',1); // 获取指定分类下的帅选属性s
    	$count = count($filter_goods_id);
    	$page = new Page($count,6);
    	if($count > 0)
    	{
    		$goods_list =M('goods a')->join('tp_group_buy b','  a.goods_id=b.goods_id','left')->field('a.goods_id,a.goods_name,a.shop_price,a.sales_sum,a.prom_id,a.prom_type,a.market_price,b.start_time,b.end_time,b.price')->where("a.goods_id","in", implode(',', $filter_goods_id))->order("$sort $sort_asc,goods_id desc")->limit($page->firstRow.','.$page->listRows)->select();
            //var_dump(M('goods')->getLastSql());
    		$filter_goods_id2 = get_arr_column($goods_list, 'goods_id');
    		if($filter_goods_id2)
    			$goods_images = M('goods_images')->where("goods_id", "in", implode(',', $filter_goods_id2))->cache(true)->select();
    	}
        /*获取当前未过期促销活动*/
        $condi['start_time']=array('elt',time());
        $condi['end_time']=array('egt',time());
        $proms=M('prom_goods')->where($condi)->select();
        $user=get_user_id();
        foreach ($proms as $k => $val) {
             if(in_array($user['level'],explode(',', $val['group']))){
                $promss[$val['id']]=$val;
             }
         }
        if($goods_list){
            foreach ($goods_list as $key => $value) {
                    if($value['prom_type']==2&&$value['start_time']<time()&&$value['end_time']>time()){ //如果是团购商品
                        $value['nowprice']=$value['price'];
                        $value['is_prom']=2;//是否是有效团购商品
                    }elseif($value['prom_type']==3){//如果是优惠促销商品
                        if(!empty($promss[$value['prom_id']])){
                            $prominfo=$promss[$value['prom_id']];
                            if($prominfo['type'] == 0){
                                $value['nowprice'] = $value['shop_price']*$prominfo['expression']/100;//打折优惠
                            }elseif($prominfo['type'] == 1){
                                $value['nowprice'] = $value['shop_price']-$prominfo['expression'];//减价优惠
                            }elseif($prominfo['type']==2){
                                $value['nowprice'] = $prominfo['expression'];//固定金额优惠
                            }else{
                                $value['nowprice'] = $value['shop_price'];
                            }
                            $value['is_prom']=3;//是否是有效促销商品
                            $value['prom_name']=$prominfo['name'];
                        }
                    }else{
                        $value['nowprice']=$value['shop_price'];
                        $value['is_prom']=0;//普通商品
                    }
                    $search_goods[]=$value;
                }
        }
    	$goods_category = M('goods_category')->where('is_show=1')->cache(true)->getField('id,name,parent_id,level'); // 键值分类数组
        $n_user = get_user_id();
        $shareLink = "http://$_SERVER[HTTP_HOST]".$_SERVER["REQUEST_URI"];
        $this->assign('shareLink',$shareLink);
        $this->assign('user',$n_user['user_id']);
    	$this->assign('goods_list',$search_goods);
    	$this->assign('goods_category',$goods_category);
    	$this->assign('goods_images',$goods_images);  // 相册图片
    	$this->assign('filter_menu',$filter_menu);  // 帅选菜单
    	$this->assign('filter_spec',$filter_spec);  // 帅选规格
    	$this->assign('filter_attr',$filter_attr);  // 帅选属性
    	$this->assign('filter_brand',$filter_brand);// 列表页帅选属性 - 商品品牌
    	$this->assign('filter_price',$filter_price);// 帅选的价格期间
    	$this->assign('goodsCate',$goodsCate);
    	$this->assign('cateArr',$cateArr);
    	$this->assign('filter_param',$filter_param); // 帅选条件
    	$this->assign('cat_id',$id);
        $this->assign('type',$type);
    	$this->assign('page',$page);// 赋值分页输出
        $this->assign('time',time());
    	$this->assign('sort_asc', $sort_asc == 'asc' ? 'desc' : 'asc');
    	C('TOKEN_ON',false);
        if(input('is_ajax')){
            return $this->fetch('ajaxGoodsList');
        }
        else{
            return $this->fetch();
        }
    }

    public function ajax_goods_desc(){
        if(IS_AJAX){
            $goods_id=I('post.goods_id');
            $goods_desc=M('goods')->where('goods_id',$goods_id)->getField('goods_content');
            echo $goods_desc;
        }
    }


    /**
     * 商品列表页 ajax 翻页请求 搜索
     */
    public function ajaxGoodsList() {
        $where ='';

        $cat_id  = I("id/d",0); // 所选择的商品分类id
        if($cat_id > 0)
        {
            $grandson_ids = getCatGrandson($cat_id);
            $where .= " WHERE cat_id in(".  implode(',', $grandson_ids).") "; // 初始化搜索条件
        }

        $result = DB::query("select count(1) as count from __PREFIX__goods $where ");
        $count = $result[0]['count'];
        $page = new AjaxPage($count,10);

        $order = " order by goods_id desc"; // 排序
        $limit = " limit ".$page->firstRow.','.$page->listRows;
        $list = DB::query("select *  from __PREFIX__goods $where $order $limit");

        $this->assign('lists',$list);
        $html = $this->fetch('ajaxGoodsList'); //return $this->fetch('ajax_goods_list');
       exit($html);
    }

    /**
     * 商品详情页
     */
    public function goodsInfo(){
        $geturl = I('dlsign');
        $getLink = geturl($geturl);
        $u_id_two = I('u_id');
        $u_id = $getLink['u_id'];
        $goods_id = I('id');
        $n_user = get_user_id();
        $dltoken = I('dltoken');
        $now_user = $n_user['user_id'];
        
        
        C('TOKEN_ON',true);
        $goodsLogic = new \app\home\logic\GoodsLogic();
        $goods_id = I("get.id/d");
       
        //检查商品是否参与促销，返回促销后商品信息
        $goods=get_goods_promotion($goods_id);

        if($goods===false){
            $this->error('此商品不存在或者已下架');
        }

        if($goods['brand_id']){
            $brnad = M('brand')->where("id", $goods['brand_id'])->find();
            $goods['brand_name'] = $brnad['name'];// 商品 品牌
        }
        $goods_images_list = M('GoodsImages')->where("goods_id", $goods_id)->select(); // 商品 图册
        $goods_attribute = M('GoodsAttribute')->getField('attr_id,attr_name'); // 查询属性
        $goods_attr_list = M('GoodsAttr')->where("goods_id", $goods_id)->select(); // 查询商品属性表

		$filter_spec = $goodsLogic->get_spec($goods_id);  
         
        $spec_goods_price  = M('spec_goods_price')->where("goods_id", $goods_id)->getField("key,price,store_count"); // 规格 对应 价格 库存表
        //M('Goods')->where("goods_id=$goods_id")->save(array('click_count'=>$goods['click_count']+1 )); //统计点击数
        $commentStatistics = $goodsLogic->commentStatistics($goods_id);// 获取某个商品的评论统计     
        $this->assign('spec_goods_price', json_encode($spec_goods_price,true)); // 规格 对应 价格 库存表
      	$goods['sale_num'] = M('order_goods')->where(['goods_id'=>$goods_id,'is_send'=>1])->count();

        $goods['discount'] = round($goods['price']/$goods['market_price'],2)*10;
       
        //当前用户收藏
        $user_id = cookie('user_id');
        $collect = M('goods_collect')->where(array("goods_id"=>$goods_id ,"user_id"=>$user_id))->count();
        $goods_collect_count = M('goods_collect')->where(array("goods_id"=>$goods_id))->count(); //商品收藏数

        if($goods['prom_type'] ==1){
            $flash_sale = M('flash_sale')->where(['id'=>$goods['prom_id'],'is_end'=>0])->find();
            $prom_goods['name']=$flash_sale['title'];
            $prom_goods['start_time']=$flash_sale['start_time'];
            $prom_goods['end_time']=$flash_sale['end_time'];
            $prom_goods['description']=$flash_sale['description'];
            $this->assign('prom_goods',$prom_goods);
        }

        //商品促销
        if($goods['prom_type'] ==3)
        {
            
            $prom_goods = M('prom_goods')->where(['id'=>$goods['prom_id'],'is_close'=>0])->find();
            $this->assign('prom_goods',$prom_goods);
        }

        /*商品分享开始*/
        $link = array(
            'u_id'=>$n_user['user_id'],
        );//url加密
        $shareLink = encrypt_param($link);
        $shareLink = "http://$_SERVER[HTTP_HOST]/index.php?m=Mobile&c=Goods&a=goodsInfo&id=$goods[goods_id]&dltoken=".$_SESSION['dltoken']."&dlsign=".$shareLink;
        $share_mdl = M('share_record');
        if ($dltoken) {
            if ($u_id_two || $u_id) {
                if ($now_user != $u_id_two) {
                    $where['s_user_id'] = $now_user;
                    $where['goods_id'] = $goods_id;
                    $share = $share_mdl->where($where)->count();
                    $where_one['user_id'] = $now_user;
                    $where_one['goods_id'] = $goods_id;
                    $share_one = $share_mdl->where($where_one)->count();
                    if ($share <= 0 && $share_one <= 0) {
                        $sWhere['s_user_id'] = $u_id;
                        $sWhere['goods_id'] = $goods_id;
                        $reShareCount = $share_mdl->where($sWhere)->count();
                        $reShare = $share_mdl->where($sWhere)->find();
                        if ($reShareCount <= 0) {
                            $add['user_id'] = $u_id;
                            $add['s_user_id'] = $now_user;
                            $add['goods_id'] = $goods_id;
                            $add['create_time'] = time();
                            $add['link'] = $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
                            if($u_id!=$now_user)
                            $share_mdl->add($add);
                        } else {
                            $add['user_id'] = $u_id;
                            $add['s_user_id'] = $now_user;
                            $add['goods_id'] = $goods_id;
                            $add['create_time'] = time();
                            $add['first_user_id'] = $reShare['user_id'];
                            $add['s_id'] = $reShare['id'];
                            $add['link'] = $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
                            if($u_id!=$now_user)
                            $share_mdl->add($add);
                        }
                    }
                }
            }
        }


         /*商品分享结束*/
        $this->assign('shareLink',$shareLink);
        $this->assign('collect',$collect);
        $this->assign('user_id',$n_user['user_id']);
        $this->assign('commentStatistics',$commentStatistics);//评论概览
        $this->assign('goods_attribute',$goods_attribute);//属性值     
        $this->assign('goods_attr_list',$goods_attr_list);//属性列表
        $this->assign('filter_spec',$filter_spec);//规格参数
        $this->assign('goods_images_list',$goods_images_list);//商品缩略图
        $this->assign('goods',$goods);
        $this->assign('goods_collect_count',$goods_collect_count); //商品收藏人数
        $this->assign('time',time());
        $this->assign('level',$n_user['level']);
        $this->assign('outer_storege',tpCache('basic.outer_storege'));
        if($goods['prom_type'] ==1){
            return $this->fetch('flashinfo');
        }elseif($goods['prom_type'] ==2){
            return $this->fetch('group');
        }else{
             return $this->fetch('goodsInfo2');
        }
        
        
    }
    public function pointgoodsInfo(){
        $goods_id = I("get.id/d");
        $point_rate = tpCache('shopping.point_rate');
        $goods = M('Goods')->where("goods_id", $goods_id)->find();
        if(empty($goods)){
            $this->error('此商品不存在或者已下架');
        }
        
        $this->assign('goods',$goods);
        $this->assign('pay_points',$pay_points);
        $this->assign('point_rate',$point_rate);
        return $this->fetch();
    }

    

    /**
     * 商品详情页
     */
    public function detail(){
        //  form表单提交
        C('TOKEN_ON',true);
        $goods_id = I("get.id/d");
        $goods = M('Goods')->where("goods_id", $goods_id)->find();
        $this->assign('goods',$goods);
        return $this->fetch();
    }

    /*
     * 商品评论
     */
    public function comment(){
        $goods_id = I("goods_id/d",0);
        $this->assign('goods_id',$goods_id);
        return $this->fetch();
    }

    /*
     * ajax获取商品评论
     */
    public function ajaxComment(){        
        $goods_id = I("goods_id/d",0);
        $commentType = I('commentType','1'); // 1 全部 2好评 3 中评 4差评
        if($commentType==5){
        	$where = "goods_id = :goods_id and parent_id = 0 and img !='' ";
        }else{
        	$typeArr = array('1'=>'0,1,2,3,4,5','2'=>'4,5','3'=>'3','4'=>'0,1,2');
        	$where = "goods_id = :goods_id and parent_id = 0 and ceil((deliver_rank + goods_rank + service_rank) / 3) in($typeArr[$commentType])";
        }
        $count = M('Comment')->where($where)->bind(['goods_id'=>$goods_id])->count();
		$page_count = 5;
        $page = new AjaxPage($count,$page_count);
        $list = M('Comment')
				->alias('c')
				->join('__USERS__ u','u.user_id = c.user_id','LEFT')
				->where($where)
				->bind(['goods_id'=>$goods_id])
				->order("add_time desc")
				->limit($page->firstRow.','.$page->listRows)
				->select();
		$replyList = M('Comment')->where(['goods_id'=>$goods_id,'parent_id'=>['>',0]])->order("add_time desc")->select();
        foreach($list as $k => $v){
            $list[$k]['img'] = unserialize($v['img']); // 晒单图片            
        }
		$this->assign('goods_id',$goods_id);//商品id
        $this->assign('commentlist',$list);// 商品评论
		$this->assign('commentType',$commentType);// 1 全部 2好评 3 中评 4差评 5晒图
        $this->assign('replyList',$replyList); // 管理员回复
		$this->assign('count', $count);//总条数
		$this->assign('page_count', $page_count);//页数
		$this->assign('current_count', $page_count*I('p'));//当前条
		$this->assign('p', I('p'));//页数
        return $this->fetch();
    }
    
    /*
     * 获取商品规格
     */
    public function goodsAttr(){
        $goods_id = I("get.goods_id/d",0);
        $goods_attribute = M('GoodsAttribute')->getField('attr_id,attr_name'); // 查询属性
        $goods_attr_list = M('GoodsAttr')->where("goods_id", $goods_id)->select(); // 查询商品属性表
        $this->assign('goods_attr_list',$goods_attr_list);
        $this->assign('goods_attribute',$goods_attribute);
        return $this->fetch();
    }

    /**
     * 积分商城
     */
    public function integralMall()
    {
        $rank= I('get.rank');
        //以兑换量（购买量）排序
        if($rank == 'num'){
            $ranktype = 'sales_sum';
            $order = 'desc';
        }
        //以需要积分排序
        if($rank == 'integral'){
            $ranktype = 'exchange_integral';
            $order = 'desc';
        }
        $point_rate = tpCache('shopping.point_rate');
        $goods_where = array(
            'is_on_sale' => 1,  //是否上架
        );
        //积分兑换筛选
        $exchange_integral_where_array = array(array('gt',0));

        // 分类id
        if (!empty($cat_id)) {
            $goods_where['cat_id'] = array('in', getCatGrandson($cat_id));
        }
        //我能兑换
        $user_id = cookie('user_id');
        if (!empty($user_id)) {
            //获取用户积分
            $user_pay_points = intval(M('users')->where(array('user_id' => $user_id))->getField('pay_points'));
            if ($user_pay_points !== false) {
                array_push($exchange_integral_where_array, array('lt', $user_pay_points));
            }
        }
        $goods_where['exchange_integral'] =  $exchange_integral_where_array;  //拼装条件
        $goods_list_count = M('goods')->where($goods_where)->count();   //总页数
        $page = new Page($goods_list_count, 15);
        $goods_list = M('goods')->where($goods_where)->order($ranktype ,$order)->limit($page->firstRow . ',' . $page->listRows)->select();
        $goods_category = M('goods_category')->where(array('level' => 1))->select();

        $this->assign('goods_list', $goods_list);
        $this->assign('page', $page->show());
        $this->assign('goods_list_count',$goods_list_count);
        $this->assign('goods_category', $goods_category);//商品1级分类
        $this->assign('point_rate', $point_rate);//兑换率
        $this->assign('totalPages',$page->totalPages);//总页数
        if(IS_AJAX){
            return $this->fetch('ajaxIntegralMall'); //获取更多
        }
        return $this->fetch();
    }

     /**
     * 商品搜索列表页
     */
    public function search(){
    	$filter_param = array(); // 帅选数组
    	$id = I('get.id/d',0); // 当前分类id
    	$brand_id = I('brand_id/d',0);    	    	
    	$sort = I('sort','a.goods_id'); // 排序
    	$sort_asc = I('sort_asc','desc'); // 排序
    	$prom_type = I('prom_type',''); // 促销类别
        $price = I('price',''); // 价钱
        $prom_id = I('prom_id',''); // 促销id
    	$start_price = trim(I('start_price','0')); // 输入框价钱
    	$end_price = trim(I('end_price','0')); // 输入框价钱
    	if($start_price && $end_price) $price = $start_price.'-'.$end_price; // 如果输入框有价钱 则使用输入框的价钱   	 
    	$filter_param['id'] = $id; //加入帅选条件中
    	$brand_id  && ($filter_param['brand_id'] = $brand_id); //加入帅选条件中    	    	
    	$price  && ($filter_param['price'] = $price); //加入帅选条件中
        $q = urldecode(trim(I('q',''))); // 关键字搜索
        $q  && ($_GET['q'] = $filter_param['q'] = $q); //加入帅选条件中
        $qtype = I('qtype','');
        $where  = array('is_on_sale' => 1);
        $where['on_time']=array('elt',time());
        $where['off_time']=array('egt',time());
        if($qtype){
        	$filter_param['qtype'] = $qtype;
        	$where[$qtype] = 1;
        }
        if($prom_id) $where['prom_id'] =$prom_id;
        if($prom_type) $where['prom_type'] =$prom_type;
        if($q) $where['goods_name'] = array('like','%'.$q.'%');
        
    	$goodsLogic = new \app\home\logic\GoodsLogic(); // 前台商品操作逻辑类
    	$filter_goods_id = M('goods')->where($where)->cache(true)->getField("goods_id",true);

    	// 过滤帅选的结果集里面找商品
    	if($brand_id || $price)// 品牌或者价格
    	{
    		$goods_id_1 = $goodsLogic->getGoodsIdByBrandPrice($brand_id,$price); // 根据 品牌 或者 价格范围 查找所有商品id
    		$filter_goods_id = array_intersect($filter_goods_id,$goods_id_1); // 获取多个帅选条件的结果 的交集
    	}

        //筛选网站自营,入驻商家,货到付款,仅看有货,促销商品
        $sel = I('sel');
        if($sel)
        {
            $goods_id_4 = $goodsLogic->get_filter_selected($sel);
            $filter_goods_id = array_intersect($filter_goods_id,$goods_id_4);
        }

    	$filter_menu  = $goodsLogic->get_filter_menu($filter_param,'search'); // 获取显示的帅选菜单
    	$filter_price = $goodsLogic->get_filter_price($filter_goods_id,$filter_param,'search'); // 帅选的价格期间
    	$filter_brand = $goodsLogic->get_filter_brand($filter_goods_id,$filter_param,'search',1); // 获取指定分类下的帅选品牌    	 
    	
    	$count = count($filter_goods_id);
    	$page = new Page($count,6);
    	if($count > 0)
    	{
    		//$goods_list = M('group_buy')->table('tp_group_buy a,tp_goods b')->where('a.goods_id=b.goods_id')->where("a.goods_id", "in", implode(',', $filter_goods_id))->order("$sort $sort_asc")->limit($page->firstRow.','.$page->listRows)->select();
            $goods_list =M('goods a')->join('tp_group_buy b',' a.goods_id=b.goods_id','left')->field('a.goods_id,a.goods_name,a.shop_price,a.sales_sum,a.prom_id,a.prom_type,a.market_price,b.start_time,b.end_time,b.price')->where("a.goods_id","in", implode(',', $filter_goods_id))->order("$sort $sort_asc,goods_id desc")->limit($page->firstRow.','.$page->listRows)->select();
            
    		$filter_goods_id2 = get_arr_column($goods_list, 'goods_id');
    		if($filter_goods_id2)
    			$goods_images = M('goods_images')->where("goods_id", "in", implode(',', $filter_goods_id2))->cache(true)->select();
    	}

         $n_user = get_user_id();
             /*获取当前未过期促销活动*/
             $condi['start_time']=array('elt',time());
             $condi['end_time']=array('egt',time());
             $proms=M('prom_goods')->where($condi)->select();
             foreach ($proms as $k => $val) {
                 if(in_array($n_user['level'],explode(',', $val['group']))){
                    $promss[$val['id']]=$val;
                 }
                 $promm[$val['id']]=$val;
             }


             if($goods_list){
                 foreach ($goods_list as $key => $value) {
                         if($value['prom_type']==2&&$value['start_time']<time()&&$value['end_time']>time()){ //如果是团购商品
                             $value['nowprice']=$value['price'];
                             $value['is_prom']=2;//是否是有效团购商品
                             $search_goods[]=$value;
                         }elseif($value['prom_type']==3){//如果是优惠促销商品
                             if(!empty($promss[$value['prom_id']])){
                                 $prominfo=$promss[$value['prom_id']];
                                 if($prominfo['type'] == 0){
                                     $value['nowprice'] = $value['shop_price']*$prominfo['expression']/100;//打折优惠
                                 }elseif($prominfo['type'] == 1){
                                     $value['nowprice'] = $value['shop_price']-$prominfo['expression'];//减价优惠
                                 }elseif($prominfo['type']==2){
                                     $value['nowprice'] = $prominfo['expression'];//固定金额优惠
                                 }else{
                                     $value['nowprice'] = $value['shop_price'];
                                 }
                                 $value['is_prom']=3;//是否是有效促销商品
                                 $value['prom_name']=$prominfo['name'];
                                 $search_goods[]=$value;
                             }
                         }elseif($value['prom_type']==1){//如果是显示抢购
                            $value['nowprice']=M('flash_sale')->where(['id'=>$value['prom_id']])->getField('price');
                            $value['is_prom']=1;//是否是有效限时抢购
                            $search_goods[]=$value;
                         }else{
                             $value['nowprice']=$value['shop_price'];
                             $value['is_prom']=0;//普通商品
                             $search_goods[]=$value;
                         }
                }
             }

             

         // 键值分类数组
    	$goods_category = M('goods_category')->where('is_show=1')->cache(true)->getField('id,name,parent_id,level'); 

    	$this->assign('goods_list',$search_goods);
        $this->assign('user',$n_user['user_id']);
        $this->assign('goods_category',$goods_category);
    	$this->assign('goods_images',$goods_images);  // 相册图片
    	$this->assign('filter_menu',$filter_menu);  // 帅选菜单     
    	$this->assign('filter_brand',$filter_brand);// 列表页帅选属性 - 商品品牌
    	$this->assign('filter_price',$filter_price);// 帅选的价格期间    	
    	$this->assign('filter_param',$filter_param); // 帅选条件    	
    	$this->assign('page',$page);// 赋值分页输出
        $this->assign('time',time());// 赋值分页输出
    	$this->assign('sort_asc', $sort_asc == 'asc' ? 'desc' : 'asc');
        $this->assign('qtype',$qtype);
        $this->assign('prom_type',$prom_type);
        $this->assign('prom',$promm[$prom_id]);
    	C('TOKEN_ON',false);
        if(input('is_ajax'))
            return $this->fetch('ajaxGoodsList');
        else
           return $this->fetch();
    }

    /**
     * 商品搜索列表页
     */
    public function ajaxSearch()
    {
        return $this->fetch();
    }

    /**
     * 品牌街
     */
    public function brandstreet()
    {
        $getnum = 9;   //取出数量
        $goods=M('goods')->where(array('is_recommend'=>1,'is_on_sale'=>1))->page(1,$getnum)->cache(true,TPSHOP_CACHE_TIME)->select(); //推荐商品
        for($i=0;$i<($getnum/3);$i++){
            //3条记录为一组
            $recommend_goods[] = array_slice($goods,$i*3,3);
        }
        $where = array(
            'is_hot' => 1,  //1为推荐品牌
        );
        $count = M('brand')->where($where)->count(); // 查询满足要求的总记录数
        $Page = new Page($count,20);
        $show = $Page->show();// 分页显示输出
        $brand_list = M('brand')->where($where)->limit($Page->firstRow.','.$Page->listRows)->order('sort desc')->select();
        $this->assign('Page',$show);  //赋值分页输出
        $this->assign('recommend_goods',$recommend_goods);  //品牌列表
        $this->assign('brand_list',$brand_list);            //推荐商品
        if(I('is_ajax')){
            return $this->fetch('ajaxBrandstreet');
        }
        return $this->fetch();
    }

    /**
     * 用户收藏某一件商品
     * @param type $goods_id
     */
    public function collect_goods()
    {
        $goods_id = I('goods_id/d');
        $result = $this->collect_goods_list(cookie('user_id'),$goods_id);
        exit(json_encode($result));
    }

    /**
     * 商品收藏
     * @param type $user_id 用户id
     * @param type $goods_id 商品id
     * @return type
     */
    public function collect_goods_list($user_id, $goods_id)
    {
        if (!is_numeric($user_id) || $user_id <= 0) return array('status' => -1, 'msg' => '必须登录后才能收藏', 'result' => array());
        //$count = M('Goods')->where("goods_id = $goods_id")->count();
        //if($count == 0)  return array('status'=>-2,'msg'=>'收藏的商品不存在','result'=>array());
        $count = M('GoodsCollect')->where("user_id",$user_id)->where("goods_id", $goods_id)->count();
        if ($count > 0) return array('status' => -3, 'msg' => '商品已收藏', 'result' => array());
        M('GoodsCollect')->add(array('goods_id' => $goods_id, 'user_id' => $user_id, 'add_time' => time()));
        return array('status' => 1, 'msg' => '收藏成功!请到个人中心查看', 'result' => array());
    }

     public function viewpic(){
        return $this->fetch();
    }

    //同步道讯库存
    public function sync_store(){
            if(IS_POST){
                $goods_id=I('post.goods_id');
                $size_color=I('post.size_color');
                $goods_sn=I('post.goods_sn');
                $type=I('post.type');
                $action=I('post.action');
                $db=C('DX_DB');
                try {  
                  $hostname = $db['hostname']; 
                  $port = $db['port'];  
                  $dbname = $db['dbname'];
                  $username = $db['username'];  
                  $pw = $db['pw']; 
                  $dbh = new PDO ("dblib:host=$hostname:$port;dbname=$dbname;charset=GBK","$username","$pw");  
                } catch (PDOException $e) {  
                  echo "Failed to get DB handle: " . $e->getMessage() . "\n";  
                  exit;  
                }
                $condi="t3.prod_cls_num ='".$goods_sn."'";
                if($type=='sku') {
                     $sku=I('post.sku');
                     $condi="t2.prod_num ='".$sku."'";
                     $spec_arr=M('spec_goods_price')->where('sku',$sku)->field('key,goods_id')->find();
                     $size_color=$spec_arr['key'];
                     $goods_id=$spec_arr['goods_id'];
                }

                 if($size_color){
                        $sku=M('spec_goods_price')->where(['goods_id'=>$goods_id,"key"=>$size_color])->getField('sku');
                        $condi="t2.prod_num ='".$sku."'";
                     }
                    // exit($sku);

                $sql="select t2.prod_num,sum(t0.stk_on_hand) as'num',t3.prod_cls_num,t4.color_name,t5.spec_name from WAREH_STK t0
                             left join product t2 on t0.prod_id = t2.prod_id
                             left join prod_cls t3 on t2.prod_cls_id = t3.prod_cls_id
                             left join prod_color t4 on t2.color_id = t4.color_id
                             left join prod_spec t5 on t2.spec_id = t5.spec_id
                             where ".$condi." group by t3.prod_cls_num,t2.prod_num ,t3.prod_name,t0.prod_id,t4.color_name ,t5.spec_name";
               
               
                $stmt = $dbh->prepare($sql);
                $stmt->execute();
                $total_num=0;
                while ($row = $stmt->fetch()){
                    $arr['prod_cls_num']=$row['prod_cls_num'];
                    $arr['prod_num']=$row['prod_num'];
                    $arr['num']=$row['num'];
                    $arr['spec_name']=$row['spec_name'];
                    $arr['color_name']= iconv('GBK', 'UTF-8', $row['color_name']); 
                    $arr['attr']=$arr['spec_name'].$arr['color_name'];
                    $datas['data'][]=$arr;
                    $total_num+=(int)$arr['num'];
                    if($arr['prod_num']==$sku){
                        $datas['current_num']=$arr['num'];
                    }
                }
                    $datas['total_num']=$total_num;
                    
                //查询已付款状态订单商品数量
                
                $goods_num=M('order_goods t0')->join('tp_order t1','t0.order_id=t1.order_id')->where(["t0.goods_id"=>$goods_id,"t0.spec_key"=>$size_color,"t1.pay_status"=>1,"t0.is_send"=>0])->sum('goods_num');

                $datas['current_num']=$datas['current_num']-$goods_num;

                if($action=="sync_store"){
                    //同步到数据库
                    $reslt['store_count']=$datas['current_num'];
                    M('spec_goods_price')->where('sku',$sku)->save($reslt);
                }
              
                echo json_encode($datas);
                unset($dbh); unset($stmt);

                
            }
        }
       
  



    /**
     * 看相似
     * $author lxl
     * $time 2017-1
     */
//    public function similar(){
//        $good_id = I('id/d','');
//        $now_good = M('goods')->where("goods_id=$good_id")->find();   //当前商品
//        $where_id_list = M('goods')->field('cat_id,spec_type')->where("goods_id=$good_id")->find(); //相似条件，分类id,类型id
//        $count = M('goods')->where($where_id_list) ->count();    //符合条件的总数
//        $pagesize = C('PAGESIZE');  //每页显示数
//        $Page = new Page($count,$pagesize);
//        $goods_list = M('goods')->where($where_id_list) ->limit($Page->firstRow.','.$Page->listRows)->select();  //获取相似商品
//        $this->assign('goods_list',$goods_list);
//        $this->assign('now_good',$now_good);
//        if(I('is_ajax')){
//            return $this->fetch('ajax_similar');
//        }
//        return $this->fetch();
//    }
}